package db

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"gorm.io/gorm"
	"goskeleton/app/core/config"
	"goskeleton/app/utils/gorm_v2"
	"os"
	"strings"
	//"io/ioutil"
)

var SqlSession *gorm.DB
var DbMysql *gorm.DB
var (
	Db1 *gorm.DB
	Db2 *gorm.DB
)

// 配置参数映射结构体
type conf struct {
	Url      string `yaml:"url"`
	UserName string `yaml:"userName"`
	Password string `yaml:"password"`
	DbName   string `yaml:"dbname"`
	Port     string `yaml:"post"`
}

func MysqlSession(ds string) {
	fmt.Printf("切换 SqlSession 为 %s \n", ds)
	var confPrams = CreateDsFactory(ds)
	db, err := gorm_v2.GetSqlDriver("mysql", 0, confPrams)
	if err != nil {
		fmt.Printf("conn false %v \n", db)

	}
	fmt.Println("SqlSession conn success ")
	SqlSession = db
}

// InitDb initializes the database.
//
// It takes a pointer to a config.Config struct as a parameter.
// It returns an error.
func InitDb(config *config.Config) (err error) {
	//初始化
	var ds1, ds2, ktg gorm_v2.ConfigParams
	ds1.Write = config.Data.DataSource.Mysql001
	ds2.Write = config.Data.DataSource.Mysql002
	ktg.Write = config.Data.DataSource.Ktgmes

	fmt.Printf("初始化 db1 config %v \n", config.Data.DataSource.Mysql001)
	fmt.Printf("初始化 db2 config %v \n", config.Data.DataSource.Mysql002)
	Db1, err = gorm_v2.GetSqlDriver("mysql", 0, ds1)
	Db2, err = gorm_v2.GetSqlDriver("mysql", 0, ds2)
	if err != nil {
		fmt.Printf("conn false %v \n", Db1)

	}
	fmt.Println("初始化ds conn success ")

	// 初始化 SqlSession
	//SqlSession = DbMysql
	MysqlSession("ds1")
	//================================================
	// 配置
	//var c conf
	//获取yaml配置参数
	//conf := c.getConf()
	//fmt.Println("app 数据源conf=========》", conf)
	//将yaml配置参数拼接成连接数据库的url
	//dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
	//	conf.UserName,
	//	conf.Password,
	//	conf.Url,
	//	conf.Port,
	//	conf.DbName,
	//)
	return
}

// 获取配置参数数据
func (c *conf) getConf() *conf {
	//读取resources/application.yaml文件
	yamlFile, err := os.ReadFile("resources/application.yaml")
	//若出现错误，打印错误提示
	if err != nil {
		fmt.Println(err.Error())
	}
	//将读取的字符串转换成结构体conf
	err = yaml.Unmarshal(yamlFile, c)
	if err != nil {
		fmt.Println(err.Error())
	}
	return c
}

// 数据源连接
func CreateDsFactory(ds string) gorm_v2.ConfigParams {
	sysConfig := config.NewConfig().ReadConfig()
	return Dbs(sysConfig, ds)
}

func Dbs(config *config.Config, ds string) gorm_v2.ConfigParams {

	var ds1, ds2 gorm_v2.ConfigParams

	fmt.Println("ds 数据源配置赋值  ")
	fmt.Printf("db01 config %v \n", config.Data.DataSource.Mysql001)
	ds1.Write = config.Data.DataSource.Mysql001
	ds2.Write = config.Data.DataSource.Mysql002
	fmt.Printf("db01 config ds1 %v \n", ds1)

	// 配置数据库
	var dbs gorm_v2.ConfigParams
	switch strings.ToLower(ds) {
	case "ds1":
		dbs = ds1
	case "ds2", "mysql002":
		dbs = ds2
	default:
		return ds1
	}
	return dbs
}
